package com.heqiang.web.servlet.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //强制转换
        HttpServletRequest request=(HttpServletRequest) req;
        //获取请求中的URI
        String uri = request.getRequestURI();
        if (uri.contains("/login.jsp")||uri.contains("/loginServlet")||uri.contains("/checkCodeServlet")||uri.contains("/css/")||uri.contains("/fonts/")||uri.contains("/js/")){
            //用户想登录
            chain.doFilter(req, resp);
        }else {
            //用户不想登陆,那么判断是否已经登陆
            Object user = request.getSession().getAttribute("asign");
            if(user!=null){
                chain.doFilter(req, resp);
            }else {
                request.setAttribute("login_msg","您尚未登陆...请先登录!");
                //转发到登陆界面
                request.getRequestDispatcher("/login.jsp").forward(request,resp);
            }
        }
        //放行chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

    public void destroy() {

    }
}
